Cars start with full (100%) batteries. Each time you drive the car using the remote control, it covers 20 meters and drains one percent of the battery. The car's nickname is not known until it is created.
The total distance it has driven, displayed as: "METERS meters".
The remaining battery charge, displayed as: "Battery at PERCENTAGE%".
If the battery is at 0%, you can't drive the car anymore and the battery display will show "Battery empty".
Implement the RemoteControlCar.new/0 function to return a brand-new remote controlled car struct.
The nickname is required by the struct, make sure that a value is initialized in the new function, but not in the struct.
Implement the RemoteControlCar.new/1 function to return a brand-new remote controlled car struct with a provided nickname.
Implement the RemoteControlCar.display_distance/1 function to return the distance as displayed on the LED display.
Make sure the function only accepts a RemoteControlCar struct as the argument.
Implement the RemoteControlCar.display_battery/1 function to return the battery percentage as displayed on the LED display.
Make sure the function only accepts a RemoteControlCar struct as the argument. If the battery is at 0%, the battery display will show "Battery empty".
Implement the RemoteControlCar.drive/1 function that:
updates the number of meters driven by 20
drains 1% of the battery
Make sure the function only accepts a RemoteControlCar struct as the argument.
Update the RemoteControlCar.drive/1 function to not increase the distance driven nor decrease the battery percentage when the battery is drained (at 0%)
https://exercism.org/tracks/elixir/exercises/remote-control-car
defmodule RemoteControlCar do
@moduledoc """
practice struct
"""
@per_driven_distance 20
@per_battery_drain 1
@enforce_keys :nickname
defstruct [:nickname, battery_percentage: 100, distance_driven_in_meters: 0]
def new(nickname \\ "none"), do: %__MODULE__{nickname: nickname}
def display_distance(%__MODULE__{} = remote_car),
do: "#{remote_car.distance_driven_in_meters} meters"
def display_battery(%__MODULE__{} = remote_car) do
battery_percentage = remote_car.battery_percentage
"Battery #{if battery_percentage !== 0, do: "at #{battery_percentage}%", else: "empty"}"
end
def drive(%RemoteControlCar{} = remote_car) do
cur_battery_percentage = remote_car.battery_percentage
if cur_battery_percentage === 0 do
remote_car
else
%{
remote_car
| battery_percentage: cur_battery_percentage - @per_battery_drain,
distance_driven_in_meters: remote_car.distance_driven_in_meters + @per_driven_distance
}
end
end
end